<template>
    <div>
        <div class="container">
            <TableCustom :columns="columns" :tableData="tableData" :hasPagination="false">
                <template #toolbarBtn>
                    <el-button type="warning" :icon="CirclePlusFilled" @click=" visible = true;">新增</el-button>
                </template>
                <template #h_status="{rows}">
                    <el-tag v-if="rows.h_status == 1" type="success">正常</el-tag>
                    <el-tag v-else type="danger">禁用</el-tag>
                </template>
                <template #operator="{rows}">
                    <el-button type="primary" @click="handleEdit(rows)">编辑角色</el-button>
                    <el-button type="warning" @click="handleRoleOption(rows)">权限配置</el-button>
                </template>
            </TableCustom>
            <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
                :close-on-click-modal="false" @close="closeDialog">
                <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData"/>
            </el-dialog>
            <el-dialog title="权限配置" v-model="primsRole" width="700px" destroy-on-close
                :close-on-click-modal="false" @close="closePrimsRoleDialog">
                <el-tree
                    v-if="primsRole"
                    style="max-width: 600px"
                    :data="primsData"
                    show-checkbox
                    ref="treeRef"
                    node-key="m_id"
                    :default-expanded-keys="defaultExpandedKeys"
                    :default-checked-keys="defaultCheckedKeys"
                    :props="primsDefaultProps"
                />
                <el-button type="warning" @click="savePrimss">保存权限</el-button>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts" name="collaborativeAdministrator-user">
import { ref, reactive, onMounted, getCurrentInstance  } from 'vue';
import { ElMessage, ElMessageBox, ElTree } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { Place } from './types/cooperUser.js';
import { query_role_list, query_module_list, query_role_module, update_role_module_list } from '@/api';
import TableCustom from '@/components/table-custom.vue';
import TableSearch from '@/components/table-search.vue';
import { FormOption, FormOptionList } from '@/types/form-option';


// 表格相关
let columns = ref([
    // { prop: 'h_user_id', label: '用户id' },
    { prop: 'r_name', label: '角色名' },
    { prop: 'r_code', label: '角色id' },
    {prop: 'r_info', label: '角色信息'},
    {prop: 'create_time', label: '创建时间'},
    { prop: 'operator', label: '操作', width: 250 },
])
const tableData = ref<Place[]>([]);
const getData = async () => {
    const res = await query_role_list({})
    tableData.value = res.data;
    // page.total = res.data.total;
};
getData();


// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '150px',
    span: 20,
    list: [
        { type: 'input', label: '角色名称', prop: 'r_name', required: true, placeholder: '请输入角色名称' },
        { type: 'textarea', label: '角色信息', prop: 'r_info', required: true, placeholder: '请输入角色信息' }
    ]
})

const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const handleEdit = (row) => {
    rowData.value = { ...row };
    isEdit.value = true;
    visible.value = true;
};
const updateData = async(value) => {
    const sentData = JSON.parse(JSON.stringify(value))
    delete sentData.h_status
    delete sentData.r_name 
    delete sentData.responsible_name
    // const res = await register_user(sentData)
    // if (res.code == '1000') {
    //     closeDialog();
    //     getData();
    // }

};
const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
};




// 删除相关
const handleDelete = (row: Place) => {
    ElMessageBox.confirm('确认要重置密码', '提示', {
        type: 'warning'
    })
        .then(async () => {
            // update_user_password({h_user_id: row.h_user_id }).then(res => {
            //     if (res.code == 1000) {
            //         ElMessage.success('重置密码成功');
            //     }
            // })
        })
        .catch(() => { });
    
}


// 权限配置
const primsRole = ref(false)
const primsData = ref([])
const selectRouter = ref([])
const defaultExpandedKeys = ref([])
const defaultCheckedKeys = ref([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const rolePrmis = ref({r_code: ''})

const primsDefaultProps =  {
  children: 'children',
  label: 'm_name',
}
query_module_list().then(res => {
    if(res.code == '1000') {
        primsData.value = res.data
    }
})
const closePrimsRoleDialog = () => {
    primsRole.value = false
}
const handleRoleOption = (row) => {
    defaultExpandedKeys.value = []
    defaultCheckedKeys.value = []
    rolePrmis.value = row
    query_role_module({role_code: row.r_code}).then(res => {
        selectRouter.value = res.data
        selectRouter.value.forEach(item => {
            defaultExpandedKeys.value.push(item.m_id)
            if (item.children.length == 0) {
                defaultCheckedKeys.value.push(item.m_id)
            }
            item.children.forEach(child => {
                defaultCheckedKeys.value.push(child.m_id)
            })
        })
        primsRole.value = true
    })
    
}
const savePrimss = (data) => {
    let checkedKeys = JSON.parse(JSON.stringify(treeRef.value.getCheckedNodes()))
    let halfCheckedKeys = JSON.parse(JSON.stringify(treeRef.value.getHalfCheckedNodes()))
    let arr = [...checkedKeys, ...halfCheckedKeys]
    if(!arr.length) return
    let parentNode = arr.filter(item =>{
        return  (item.children = []) && !item.m_father_id
    })
    let ChildrenNode = arr.filter(item => !!item.m_father_id)
    parentNode.forEach(item => {
        ChildrenNode.forEach(child => {
            if(child.m_father_id == item.m_id) {
                item.children.push(child)
            }
        })
    })
    update_role_module_list({role_code: rolePrmis.value.r_code, model_list: parentNode}).then(res => {
       if(res.code == '1000') {
            ElMessage.success('权限设置成功');
            primsRole.value = false
            defaultExpandedKeys.value = []
            defaultCheckedKeys.value = []
       }
    })
   
}
</script>

<style scoped></style>